
-- 一般登入
local httparg               = require("shared.api.httparg")
local response              = require("shared.api.response")
local config                = require("config")
local tag                   = httparg.tag()
local assertion             = httparg.assertion
local httpclient            = require "shared.http.client"
local util                  = require "proxy.game.common.util"

local ngx                   = _G.ngx
local get_response_spec     = util.get_response_spec
local fill_response_header  = util.fill_response_header
local is_match_content_type = util.is_match_content_type
local get_content_decoder   = util.get_content_decoder
local get_method            = util.get_method


local cjson = require "cjson.safe"
      cjson.encode_max_depth(32)
      cjson.decode_max_depth(32)

local ACCESS_TOKEN_TTL = config.VAR.ACCESS_TOKEN_TTL



local ARGS = {
  tag.body('json', 'required'),

  username  = tag.json.username  ('string', 'required'),
  password  = tag.json.password  ('string', 'required'),
  adjust    = tag.json.adjust    ('map'),
}
--調用nsq
local ip = ngx.req.get_headers()['IP']
  ngx.log(ngx.ERR,ip)
local call_nsq=function(regRes)
    --nsq
    regRes.ip = ip
    local producer = require "resty.nsq.producer"
    local NSQ= config._Event_Bus_Nsq

    local prod = producer:new()
   local ok, err = prod:connect(NSQ.host,NSQ.port)
   -- local ok, err = prod:connect("10.101.137.80",4150)
   -- Event_Bus_Nsq_Pub_Address: "10.101.113.74:4150"

    if not ok then
        ngx.say("failed to connect: ", err)
        return
    end
    local nsqMsg= regRes
    local NSQ_MSG_BODY= cjson.encode(nsqMsg)
    ngx.log(ngx.ERR, NSQ_MSG_BODY)
  local  ok, err = prod:pub(NSQ.active,NSQ_MSG_BODY )
    if not ok then
        ngx.say("failed to pub: ", err)
        return
    end
    ok, err = prod:close()
    if not ok then
        ngx.say("failed to close: ", err)
        return
    end

end

--调用dataGateway实际登录
local resonseReal=function()
  local headers = ngx.req.get_headers()

  ARGS.login_ip = ip
  --ngx.log(ngx.ERR,clientIP)

  --根ulr
  local ADDRESS = config.ENV.DATAGATE_SERVICE
  --后面接的path
  local ACTION  = string.format("%s/account",ngx.var.oauth_brand)


    ngx.log(ngx.ERR,"begin 1")
  if not ADDRESS or not ACTION then
    ngx.status = ngx.HTTP_NOT_FOUND
    ngx.exit(ngx.OK)
  end
    ngx.log(ngx.ERR,"begin 1")
  local location = ngx.unescape_uri(ADDRESS..ACTION)
  local method   = "VERIFY"
  local headers  = ngx.req.get_headers()
  ngx.req.read_body()

  local data=cjson.encode(ARGS)


  local query  = ngx.var.args

  do
    -- add X-Forwarded-For header
    headers['X-Forwarded-For'] = ngx.var.proxy_add_x_forwarded_for
  end

    ngx.log(ngx.ERR,"begin 1")

  --移除方法设定
  local rmvLowKey = "x-http-method-override"
  --移除gzip设定
  local rmvKey2   = "accept-encoding"
  for k,v in pairs(headers) do
     local low = string.lower(k)
     if low==rmvLowKey  or low==rmvKey2   then
       headers[k]=nil
     end
  end


  headers['X-HTTP-Method-Override'] = method

  -- perform http request
  local resp, err = httpclient.new()
    :uri(location)
    :headers(headers)
    :query(query)
    :body(data)
    :send(method, 2000, nil)

  if err or (not resp) then
    ngx.status = 500
    ngx.say(err)
    ngx.exit(ngx.OK)
  end

  -- response
  ngx.header['Server']       = ngx.var.SERVICE_NAME
  ngx.header['Content-Type'] = resp.headers['Content-Type']
  ngx.status                 = resp.status

  local rmvLowKey="content-length"
  --如果我们修改了回应的内容，不是和调用的service返回的长度一样，"content-length"需要拿掉，不然回复出去的长度对不上
  for k,v in pairs(resp.headers) do
     local low = string.lower(k)
     if low==rmvLowKey then
      resp.headers[k] = nil
     end
  end
  fill_response_header(resp.headers)


  local replyInfo=resp.body
  local regRes=cjson.decode(replyInfo)
  if  regRes and regRes.account then
      --成功了
      --replyInfo=cjson.encode({timestamp=ngx.time()})
    --verify返回确实，后面verify拿，或者直接从别的接口从datagateway取 需要完善
    regRes.status = "activated"
    replyInfo     = cjson.encode(regRes)
    -- 登录失败ocp不发送nsq
    call_nsq(regRes)
  else
      --失败了，打印信息
      if resp.body then
        ngx.log(ngx.ERR,"dataService resonpce err"..resp.body)
      else
        ngx.log(ngx.ERR,"dataService resonpce err")
      end
  end


  --adjust
  do
    ngx.log(ngx.ERR, "adjust绑定-login1:", cjson.encode(regRes))
    ngx.log(ngx.ERR, "adjust绑定-login2:", cjson.encode(ARGS))
    if regRes and ARGS.adjust then --and regRes.create_at == regRes.update_at
      ngx.log(ngx.ERR, "adjust绑定-login3:")
      local dataapi    = require("shared.api.dataapi")
      local adjustArgs = ARGS.adjust
      local reply, err = dataapi.adjust_device.create(
        {
          account     = regRes.account or "",
          adid        = adjustArgs.adid or "",
          adid_type   = adjustArgs.adid_type or "",
          app_id      = adjustArgs.app_id or "",
          device_info = adjustArgs.device_info or nil,
        })
      if err then
        if err.message ~= "DUPLICATE_DEVICE" then
          ngx.log(ngx.ERR, "adjust绑定失败：", cjson.encode(err))
        end
      end
    end
  end


  ngx.say(replyInfo)
  ngx.exit(ngx.OK)
end


resonseReal()